﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HRX.PayCenter.Common
{
    public static class ExtensionHelper
    {
        public static DateTime defaultTime = new DateTime(1900, 1, 1);

        /// <summary>
        /// 字典转字符串
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static string ToStringFromDict(this IDictionary<string, string> dict)
        {
            if (dict == null || !dict.Any())
            {
                return "";
            }
            return string.Join("&", dict.Select(kv => $"{kv.Key}={kv.Value}"));
        }

        public static string ToStringFromDict<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> dict)
        {
            if (dict == null || !dict.Any())
            {
                return "";
            }
            return string.Join("&", dict.Select(kv => $"{kv.Key}={kv.Value}"));
        }

        /// <summary>
        /// 转类似 yyyy-MM-dd HH:mm:ss 格式为时间类型
        /// 2018-10-24 00:48:47
        /// </summary>
        /// <param name="yyyyMMhh"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(this string yyyyMMddHHmmss)
        {
            DateTime dt;
            if (DateTime.TryParse(yyyyMMddHHmmss, out dt))
            {
                return dt;
            }

            return defaultTime;
        }

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
        {
            if (enumerable == null || !enumerable.Any())
            {
                return true;
            }

            return false;
        }

        public static bool IsNullOrEmpty(this IDictionary<string, string> dict)
        {
            if (dict == null || !dict.Any())
            {
                return true;
            }

            return false;
        }

        public static bool IsNullOrEmpty(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }

            return true;
        }

        public static string CutIfTooLong(this string str, int len = 400)
        {
            if (!string.IsNullOrEmpty(str) && str.Length > len)
            {
                return str.Substring(0, len);
            }

            return str;
        }

        public static string TrimOrEmpty(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }

            return str.Trim();
        }
    }
}
